package com.lhf.springcloud.service;

import com.lhf.springcloud.DAO.StudentDao;
import com.lhf.springcloud.Entity.StudentBasicInfo;
import com.lhf.springcloud.Entity.StudentInfo;
import com.lhf.springcloud.config.StorageProperties;
import com.lhf.springcloud.exception.StorageException;
import com.lhf.springcloud.exception.StorageFileNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Stream;

/**
 * @ClassName: StorangeServiceImpl
 * @Description:
 * @Author: liuhefei
 * @Date: 2019/4/1
 * @blog: https://www.imooc.com/u/1323320/articles
 **/
@Service
public class StorangeServiceImpl{

    private final Path rootLocation;

    @Autowired
    public StorangeServiceImpl(StorageProperties storageProperties){
        this.rootLocation = Paths.get(storageProperties.getLocation());
    }

    public void init() {
        try {
            Files.createDirectories(rootLocation);
        }catch (IOException e){
            throw new StorageException("Could not initialize storage", e);
        }

    }
    @Autowired
    private StudentDao studentDao;

    public String addCourse(List<StudentInfo> course) {

        /*在学生基础数据表里面查询身份证是否存在*/
        for (int i=0;i<course.size();i++){
            List<StudentBasicInfo> byStudentIdCard = studentDao.findByStudentIdCard(course.get(i).getIdCard());
            if (byStudentIdCard.size()==0){
                course.get(i).setInfoJudge("false1");
                //return "学生基础信息中没有身份证为'"+course.get(i).getIdCard()+"',姓名为'"+course.get(i).getStudentName()+"',请检查该学生的身份证信息是否准确再上传数据";
            }
            if (byStudentIdCard.size()>1){
                return "联系管理员，基础数据身份证号码重复";
            }
            if (byStudentIdCard.size()==1){
                if (!byStudentIdCard.get(0).getStudentName().equals(course.get(i).getStudentName())){
                    course.get(i).setInfoJudge("false2");
                    //return "身份证为'"+course.get(i).getIdCard()+"',姓名为'"+course.get(i).getStudentName()+"',请检查该学生的姓名是否准确再上传数据";
                }
            }
        }
        for (int i=0;i<course.size();i++){
            studentDao.addCourse(course.get(i));
        }
        return "完成操作";
    }


    public void store(MultipartFile file) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if(file.isEmpty()){
                throw new StorageException("Failed to store empty file " + filename);
            }
            if(filename.contains("..")){
                throw new StorageException("Cannot store file with relative path outside current directory " + filename);
            }
            try(InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
            }
        }catch (IOException e){
            throw new StorageException("Failed to store file " + filename, e);
        }
    }



    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1).filter(path -> !path.equals(this.rootLocation)).map(this.rootLocation::relativize);
        }catch (IOException e){
            throw new StorageException("Failed to read stored files", e);
        }
    }


    public Path load(String filename) {
       return rootLocation.resolve(filename);
    }


    public Resource loadResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new StorageFileNotFoundException("Could not read file: " + filename);
            }
        } catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    public List<StudentInfo> findAllData() {
        List<StudentInfo> data = studentDao.findAllData();
        return data;
    }

    public void updateData(String dataValue,String id,String dataName) {
        studentDao.updateData(dataValue,id,dataName);//修改的同时初始化infoJudge字段为null
        //拿到修改对象的数据
        StudentInfo byStudentId = studentDao.findByStudentId(id);
        //判断基础数据中是否存在
            List<StudentBasicInfo> byStudentIdCard = studentDao.findByStudentIdCard(byStudentId.getIdCard());
            if (byStudentIdCard.size()==0){
                studentDao.updateStudentStatus("false1",id);
                //return "学生基础信息中没有身份证为'"+course.get(i).getIdCard()+"',姓名为'"+course.get(i).getStudentName()+"',请检查该学生的身份证信息是否准确再上传数据";
            }
            else if (byStudentIdCard.size()==1){
                if (!byStudentIdCard.get(0).getStudentName().equals(byStudentId.getStudentName())){
                    studentDao.updateStudentStatus("false2",id);
                    //return "身份证为'"+course.get(i).getIdCard()+"',姓名为'"+course.get(i).getStudentName()+"',请检查该学生的姓名是否准确再上传数据";
                }else {
                    studentDao.updateStudentStatus(null,id);
                }
            }

        }


    public List<StudentInfo> findStudentByYear(String year) {
        String years=year+"级";
        List<StudentInfo> list= studentDao.findStudentByYear(years);
        if (list.size()==1){
            String gender = list.get(0).getGender();
            if (gender.equals("男")){
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setGender("女");
                studentInfo.setStudentName("0");
                list.add(studentInfo);
            }
            if (gender.equals("女")){
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setGender("男");
                studentInfo.setStudentName("0");
                list.add(studentInfo);
            }
        }
        if (list.size()==0){
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setGender("女");
                studentInfo.setStudentName("0");
                list.add(studentInfo);

                StudentInfo studentInfo1 = new StudentInfo();
                studentInfo1.setGender("男");
                studentInfo1.setStudentName("0");
                list.add(studentInfo1);

        }
        return list;
    }
}
